import type {sseOption} from "./@types/index.d"

/**
 * sse 服务端推送
 * @param {Object} option
 * @param {String} option.url 服务端地址
 * @param {String} option.data 需要发送的数据
 * @param {Function} [option.onopen] 连接打开回调
 * @param {Function} option.onmessage 接收到消息回调
 * @param {Function} [option.onerror] 连接错误回调
 * @param {Function} [option.onclose] 连接关闭回调
 * @returns {Object} sse对象
 * */ 
export default function(option : sseOption){
    let options : sseOption = {
        url: "",
        data: "",
        onopen: (e)=>{},
        onmessage: (e)=>{},
        onerror: (e)=>{},
        onclose: ()=>{},
    }
    Object.assign(options, option);
    const params = encodeURI(JSON.stringify(options.data));
    let sse = new EventSource(options.url + "?param=" + params);
    sse.onopen = function (event) {
        options.onopen?.(event);
    }

    sse.onmessage = function (event) {
        options.onmessage(event);
        if(event.data === "[[END]]"){
            sse.close();
            return;
        }
    }

    sse.onerror = function (event) {
        options.onerror?.(event);
    }

    sse.close = function () {
        options.onclose?.();
    }

    return sse;
}